package com.syqc.choose.teamcar

import android.app.Activity
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.syqc.comlib.base.LazyFragment
import com.syqc.comlib.utils.loadGif
import com.syqc.comlib.utils.loadStringDImgError
import com.syqc.comlib.utils.setResultTo
import com.syqc.comlib.utils.sub
import com.syqc.comlib.utils.subPlate
import com.syqc.comlib.utils.toast
import com.syqc.entity.TeamsAndCars
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentChooseCarBinding
import com.syqc.monitor.databinding.IncludeChooseTeamCarBinding
import com.syqc.utils.ChooseCars
import com.syqc.utils.Keys

/**
 *@Author Jasper
 *@Time   2020/7/22
 *@Desc   选择车辆
 */
class CarsFragment(
    private val isVideo: Boolean = false,
    private val isChange: Boolean = false
) :
    LazyFragment<FragmentChooseCarBinding>(FragmentChooseCarBinding::inflate) {
    private lateinit var mChooseTeamVB: IncludeChooseTeamCarBinding
    private val mViewModel: com.syqc.choose.teamcar.CarsVM by viewModels()
    private val mAdapter by lazy { ChooseCarAdapter(isVideo) }

    private var teamsAndCars: TeamsAndCars? = null

    //空布局
    private val emptyView by lazy {
        val view = layoutInflater.inflate(
            R.layout.layout_empty_view,
            binding.includeRecycler.recyclerView,
            false
        )
        view.findViewById<ImageView>(R.id.ivNoData).loadGif(requireContext(), R.mipmap.ic_empty)
        view
    }

    override fun initView(view: View) {
        mViewModel.isVideo = isVideo
        mChooseTeamVB = IncludeChooseTeamCarBinding.bind(binding.root)
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        mViewModel.initTeam()
        mViewModel.getTeamsCars()
        initRecycler()
    }

    override fun initData() {
        mViewModel.carsLive.observe(this) {
            if (it.isNullOrEmpty()) {
                mAdapter.setEmptyView(emptyView)
            } else {
                mAdapter.setNewInstance(it)
            }
        }

        mViewModel.nameLive.observe(this) {
            mChooseTeamVB.tvTeamName.text = it
        }

        mViewModel.changeTeamLive.observe(this) {
            if (it == -1) {
                putCarInfo(teamsAndCars!!)
            } else {
                putCarInfo(teamsAndCars!!, it == 0)
            }
        }
    }

    override fun initEvent() {
        mChooseTeamVB.tvTeamBack.setOnClickListener {
            mViewModel.getPrevious()
        }
        mChooseTeamVB.tvTeamHome.setOnClickListener {
            mViewModel.getRootTeam()
        }
    }

    //初始化
    private fun initRecycler() {
        binding.includeRecycler.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.includeRecycler.recyclerView.adapter = mAdapter

        mAdapter.setOnItemClickListener { _, _, position ->
            val entity = mAdapter.data[position]
            teamsAndCars = entity

            if (entity.carId != null) {
                if (isChange) {
                    mViewModel.changeTeam(entity.carId)
                } else {
                    putCarInfo(entity)
                }
            } else {
                if (entity.carNum == 0) {
                    R.string.toast_choose_no_car.toast(requireContext())
                    return@setOnItemClickListener
                }
                mViewModel.getTeamCar(entity.teamId!!, entity.teamName!!)
                binding.includeRecycler.recyclerView.scrollToPosition(0)
            }
        }
    }

    private fun putCarInfo(entity: TeamsAndCars) {
        mViewModel.saveData()
        entity.run {
            ChooseCars.addCars(
                carId = carId!!,
                carPlate = plate!!,
                carName = carName!!,
                videos = videos,
                iconLink = iconLink!!,
                isVideo = !videos.isNullOrEmpty()
            )
            setResultTo(activity as Activity) {
                putExtra(Keys.INTENT_CAR_ID, carId)
                putExtra(Keys.INTENT_CAR_NAME, subPlate(plate, 14))
                putExtra(Keys.INTENT_TEAM_NAME, teamName)
                if (videos != null) putExtra(Keys.VIDEO, videos)
            }
            requireActivity().finish()
        }
    }

    private fun putCarInfo(entity: TeamsAndCars, noAuth: Boolean = false) {
        mViewModel.saveData()
        entity.run {
            ChooseCars.addCars(
                carId = carId!!,
                carPlate = plate!!,
                carName = carName!!,
                videos = videos,
                iconLink = iconLink!!,
                isVideo = !videos.isNullOrEmpty()
            )
            setResultTo(activity as Activity) {
                putExtra(Keys.INTENT_CAR_ID, carId)
                putExtra(Keys.INTENT_CAR_NAME, subPlate(plate, 14))
                putExtra(Keys.INTENT_TEAM_NAME, teamName)
                putExtra(Keys.INTENT_NO_AUTH, noAuth.toString())
                if (videos != null) putExtra(Keys.VIDEO, videos)
            }
            requireActivity().finish()
        }
    }


}

class ChooseCarAdapter(private val isVideo: Boolean) :
    BaseQuickAdapter<TeamsAndCars, BaseViewHolder>(R.layout.item_choose_car) {

    private val accDesc by lazy { context.getString(R.string.desc_ACC) }
    private val videoDesc by lazy { "(${context.getString(R.string.desc_choose_video)})" }

    override fun convert(holder: BaseViewHolder, item: TeamsAndCars) {
        val tvName = holder.getView<TextView>(R.id.tvItemName)
        item.run {
            val plateName =
                sub(if (carName == plate) carName ?: "" else "$plate($carName)", 20)
            tvName.isSelected = item.noAuth
            if (carId.isNullOrEmpty()) {
                val num = if (isVideo) videoNum else carNum
                tvName.text = "${teamName} ($num)"
                holder.setImageResource(R.id.ivItemPic, R.mipmap.ic_team_pic)
            } else {
                val video = if (isVideo) {
                    videoDesc
                } else {
                    ""
                }
                if (acc.isNullOrEmpty()) {
                    tvName.text = "$plateName $video"
                } else {
                    tvName.text = "$plateName[$accDesc $acc]$video"
                }

                holder.getView<ImageView>(R.id.ivItemPic)
                    .loadStringDImgError(context, iconLink ?: "", R.mipmap.ic_car_location_no)
            }
        }

    }
}